package com.grts.mall.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grts.mall.common.CommonResult;
import com.grts.mall.mapper.CartMapper;
import com.grts.mall.mapper.OrderItemMapper;
import com.grts.mall.mapper.OrderMapper;
import com.grts.mall.mapper.ProductMapper;
import com.grts.mall.pojo.Cart;
import com.grts.mall.pojo.CartKey;
import com.grts.mall.pojo.Order;
import com.grts.mall.pojo.OrderItem;
import com.grts.mall.pojo.Product;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderItemMapper orderItemMapper;

	@Autowired
	private CartMapper cartMapper;

	@Override
	@Transactional
	public CommonResult add(List<Cart> vos) {
		HashMap<Cart, Product> hashMap = new HashMap<Cart,Product>();

		for (Cart vo : vos) {
			Product pro = this.productMapper.selectByPrimaryKey(vo.getPid());
			hashMap.put(vo, pro);
			if (pro.getStock() < vo.getQuantity()) {
				throw new RuntimeException("商品" + pro.getTitle() + "库存不足");
			} else {
				pro.setStock(pro.getStock() - vo.getQuantity());
				this.productMapper.updateByPrimaryKeySelective(pro);
			}
		}

		BigDecimal totalMoney = new BigDecimal("0");
		for (Entry<Cart, Product> cart : hashMap.entrySet()) {
			BigDecimal pri = cart.getValue().getPrice();
			BigDecimal quan = new BigDecimal(cart.getKey().getQuantity());
			BigDecimal all = pri.multiply(quan);
			totalMoney = totalMoney.add(all);
		}
		
		Long uid = vos.get(0).getUid();
		Order order = new Order();
		order.setCreateTime(new Date());
		order.setState(1);
		order.setTotalAmount(totalMoney);
		order.setUid(uid);
		this.orderMapper.insert(order);

		Long oid = order.getOid();
		System.out.println(oid);

		for (Cart cart : vos) {
			OrderItem orderItem = new OrderItem();
			orderItem.setOid(oid);
			orderItem.setPid(cart.getPid());
			orderItem.setQuantity(cart.getQuantity());

			this.orderItemMapper.insert(orderItem);
			CartKey key = new CartKey();
			key.setPid(cart.getPid());
			key.setUid(cart.getUid());
			this.cartMapper.deleteByPrimaryKey(key);
		}
		return CommonResult.success("下单成功",order);
	}

	@Override
	public Order findById(Long oid) {
		Order order = this.orderMapper.selectByPrimaryKey(oid);
		
		return order;
	}
}
